<template>
  <div class="app-container" v-loading="loading">
    <el-backtop visibility-height="10"></el-backtop>
    <el-row>
      <el-form :model="conditions" size="small" :inline="true" label-width="68px">
        <el-form-item label="公告标题" prop="notice_title">
          <el-input v-model="conditions.notice_title" placeholder="请输入公告标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="操作人员" prop="create_by">
          <el-input v-model="conditions.create_by" placeholder="请输入操作人员" clearable></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="create_time">
          <el-date-picker
            v-model="conditions.create_time"
            type="daterange"
            format="yyyy-MM-DD" value-format="yyyy-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="公告类型" prop="notice_type">
          <el-select v-model="conditions.notice_type" placeholder="公告类型" clearable>
            <el-option label="通知" value="1"/>
            <el-option label="公告" value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="公告状态" prop="yesapi_sys_notice_status">
          <el-select v-model="conditions.yesapi_sys_notice_status" placeholder="公告状态" clearable>
            <el-option label="正常" value="0"/>
            <el-option label="关闭" value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-search"
            type="primary"
            @click="query"
            :loading="loading"
          >
            搜索
          </el-button>
          <el-button
            icon="el-icon-refresh"
            @click="reset"
            :loading="loading"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" :loading="createNoticeBtnLoading"
                   @click="openNoticeDialog"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
                   @click="openEditNoticeDialog"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDeleteNotice"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-message" size="mini" :disabled="single"
                   @click="handleArticleDetails"
        >预览
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table
        :data="notices"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="编号" type="index" align="center"></el-table-column>
        <el-table-column label="公告标题" prop="notice_title" align="center"></el-table-column>
        <el-table-column label="公告类型" prop="notice_type" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.notice_type === 1" type="success">{{ '通知' }}</el-tag>
            <el-tag v-else-if="scope.row.notice_type === 2" type="warning">{{ '公告' }}</el-tag>
            <div v-else></div>
          </template>
        </el-table-column>
        <el-table-column label="公告状态" prop="yesapi_sys_notice_status" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.yesapi_sys_notice_status"
              :active-value="0"
              :inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="admin" align="center"></el-table-column>
        <el-table-column
          label="创建时间" align="center"
          width="150"
        >
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ msToDate(scope.row.create_time).withoutTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="阅读次数" prop="read_num" align="center" width="100"></el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-reading"
                       @click="handleArticleDetails(scope.row.id)"
            >详情
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit"
                       @click="openEditNoticeDialog(scope.row.id)"
            >修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete"
                       @click="handleDeleteNotice(scope.row.id)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row type="flex" justify="center" style="margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="conditions.currentPage"
        :page-sizes="[10, 25, 50, 100]"
        :page-size="conditions.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="notices_total"
      >
      </el-pagination>
    </el-row>
    <el-dialog
      :title="insertOrUpdateNoticeDialogTitle"
      :visible.sync="insertOrUpdateNoticeDialogVisible"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handleInsertOrUpdateNoticeDialogClose"
    >
      <div v-loading="insertOrUpdateNoticeDialogLoading">
        <el-form ref="notice_form" :model="notice" :rules="rules" label-width="80px">
          <el-row type="flex" :gutter="10">
            <el-col>
              <el-form-item label="通知标题" prop="notice_title">
                <el-input type="text" v-model="notice.notice_title" maxlength="25" style="width: 390px" show-word-limit
                          clearable
                />
              </el-form-item>
              <el-form-item label="通知类型" prop="notice_type">
                <el-select v-model="notice.notice_type" style="width: 390px">
                  <el-option label="通知" :value="1"></el-option>
                  <el-option label="公告" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="通知状态" prop="yesapi_sys_notice_status">
                <el-radio-group v-model="notice.yesapi_sys_notice_status">
                  <el-radio :label="0">正常</el-radio>
                  <el-radio :label="1">关闭</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="通知备注" prop="remark">
                <el-input type="textarea" v-model="notice.remark" maxlength="200" :autosize="{ minRows: 7, maxRows: 7}"
                          resize="none" show-word-limit clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="通知内容" prop="content">
            <v-md-editor v-model="notice.content"
                         style="height: 350px"
                         :disabled-menus="[]"
                         @upload-image="handleUploadImage"
            ></v-md-editor>
          </el-form-item>
        </el-form>
        <el-row type="flex" justify="end" style="margin-top: 50px">
          <el-button type="primary" @click="handleNoticeUpdate">修 改</el-button>
          <el-button @click="handleInsertOrUpdateNoticeDialogClose">取 消</el-button>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog
      title="预览"
      :visible.sync="previewDialogVisible"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handlePreviewDialogClose"
    >
      <div v-loading="previewDialogLoading">
        <v-md-preview :text="previewContent.content"></v-md-preview>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { msToDate } from '@/utils/format'
import axios from 'axios'
import { getToken } from '@/utils/auth'

export default {
  name: 'Notice',
  data() {
    return {
      loading: false,
      createNoticeBtnLoading: false,
      server: window.application.minio_host,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      notice_id: '',
      conditions: {
        notice_title: '',
        create_by: '',
        notice_type: '',
        create_time: [],
        yesapi_sys_notice_status: '',
        currentPage: 1,
        size: 10
      },

      insertOrUpdateNoticeDialogTitle: '',
      insertOrUpdateNoticeDialogVisible: false,
      insertOrUpdateNoticeDialogLoading: false,
      notice: {
        id: '',
        notice_title: '',
        notice_type: 1,
        yesapi_sys_notice_status: 1,
        remark: '',
        content: ''
      },
      rules: {
        notice_title: [
          { required: true, message: '通知标题不能为空', trigger: ['blur', 'change'] },
          { min: 2, max: 25, message: '岗位名称长度必须介于 2 和 25 之间', trigger: ['blur', 'change'] }
        ],
        notice_type: [
          { required: true, message: '通知类型不能为空', trigger: ['blur', 'change'] }
        ],
        yesapi_sys_notice_status: [
          { required: true, message: '公告状态不能为空', trigger: ['blur', 'change'] }
        ],
        content: [
          { required: true, message: '通知内容不能为空', trigger: ['blur', 'change'] }
        ]
      },

      previewDialogVisible: false,
      previewDialogLoading: false,
      previewContent: {
        id: '',
        notice_id: '',
        content: ''
      },
    }
  },
  mounted() {
    this.query()
  },
  computed: {
    ...mapGetters(['notices', 'notices_total'])
  },
  methods: {
    msToDate,
    query() {
      let _that = this
      this.loading = true
      this.$store.dispatch('notice/getNotices', this.conditions)
        .then((resp) => {
        })
        .catch((error) => {
          this.$message.error(error)
        }).finally(() => {
        setTimeout(() => {
          _that.loading = false
        }, 1500)
      })
    },
    reset() {
      this.conditions = {
        notice_title: '',
        create_by: '',
        notice_type: '',
        create_time: [],
        yesapi_sys_notice_status: '',
        currentPage: 1,
        size: 10
      }
      this.query()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    openNoticeDialog() {
      this.createNoticeBtnLoading = true
      this.$store.dispatch('notice/createNotice')
        .then((resp) => {
          if (resp !== undefined) {
            this.notice_id = resp
            this.insertOrUpdateNoticeDialogTitle = '添加通知'
            this.insertOrUpdateNoticeDialogVisible = true
            this.insertOrUpdateNoticeDialogLoading = true
            this.$store.dispatch('notice/getNoticeAllById', this.notice_id)
              .then((resp) => {
                this.notice = resp
              }).catch((error) => {
              this.insertOrUpdateNoticeDialogVisible = false
              this.$message.error(error)
            }).finally(() => {
              setTimeout(() => {
                this.$refs.notice_form.resetFields()
                this.insertOrUpdateNoticeDialogLoading = false
              }, 1500)
            })
          } else {
            this.$message.error('系统error')
          }

        }).catch((error) => {
        this.$message.error(error)
      }).finally(() => {
        setTimeout(() => {
          this.createNoticeBtnLoading = false
        }, 1500)
      })
    },
    openEditNoticeDialog(arg) {
      this.insertOrUpdateNoticeDialogTitle = '编辑通知'
      this.insertOrUpdateNoticeDialogVisible = true
      this.insertOrUpdateNoticeDialogLoading = true
      if (arg instanceof PointerEvent) {
        this.$store.dispatch('notice/getNoticeAllById', this.ids[0])
          .then((resp) => {
            this.notice = resp
          }).catch((error) => {
          this.insertOrUpdateNoticeDialogVisible = false
          this.$message.error(error)
        }).finally(() => {
          setTimeout(() => {
            this.insertOrUpdateNoticeDialogLoading = false
          }, 1500)
        })
      } else {
        this.$store.dispatch('notice/getNoticeAllById', arg)
          .then((resp) => {
            this.notice = resp
          }).catch((error) => {
          this.insertOrUpdateNoticeDialogVisible = false
          this.$message.error(error)
        }).finally(() => {
          setTimeout(() => {
            this.insertOrUpdateNoticeDialogLoading = false
          }, 1500)
        })
      }
    },
    handleDeleteNotice(arg) {
      if (arg instanceof PointerEvent) {
        this.$confirm(`此操作将永久删除这些通知和公告?，是否继续`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          // 确定事件
          this.$store.dispatch('notice/removeNoticesByIds', { 'ids': this.ids })
            .then(resp => {
              if (resp) {
                this.$message.success(`删除成功! `)
              } else {
                this.$message.error(`删除失败，请联系管理员`)
              }
            })
            .catch(error => this.$message.error(error))
            .finally(() => this.query())
        }).catch(() => {
        })
      } else {
        this.$confirm(`是否删除该通知和公告? ，是否继续`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          // 确定事件
          this.$store.dispatch('notice/removeNoticesByIds', { 'ids': [arg] })
            .then(resp => {
              if (resp) {
                this.$message.success(`删除成功! `)
              } else {
                this.$message.error(`删除失败，请联系管理员`)
              }
            })
            .catch(error => this.$message.error(error))
            .finally(() => this.query())
        }).catch(() => {
        })
      }
    },
    handleArticleDetails(id) {
      if (id instanceof PointerEvent) {
        this.handleNoticeDetails(this.ids[0])
      } else {
        this.handleNoticeDetails(id)
      }
    },
    handleNoticeDetails(id) {
      this.previewDialogVisible = true
      this.previewDialogLoading = true
      this.$store.dispatch('notice/getPreviewNewsContent', id)
        .then((resp) => {
          this.previewContent = resp.data.data
          setTimeout(() => {
            this.previewDialogLoading = false
          }, 1500)
        }).catch((error) => {
        this.$message.error(error)
      })
    },
    handlePreviewDialogClose() {
      this.previewContent = {
        id: '',
        notice_id: '',
        content: ''
      }
      this.previewDialogVisible = false
      this.previewDialogLoading = false
    },
    handleSizeChange(size) {
      this.conditions.size = size
      this.query()
    },
    handleCurrentChange(page) {
      this.conditions.currentPage = page
      this.query()
    },
    handleStatusChange(row) {
      let text = row.yesapi_sys_notice_status === 0 ? '启用' : '停用'
      let type = row.notice_type === 1 ? '通知' : '公告'
      this.$confirm(`确认要 ${text} 该${type}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('notice/changeState', row)
          .then((resp) => {
            if (resp.data) this.$message({ type: 'success', message: `成功 ${text} 该${type}` })
            this.query()
          })
      }).catch(() => {
        row.yesapi_sys_notice_status = row.yesapi_sys_notice_status === 0 ? 1 : 0
      })
    },
    resetNotice() {
      this.insertOrUpdateNoticeDialogVisible = false
      this.insertOrUpdateNoticeDialogTitle = ''
      this.insertOrUpdateNoticeDialogLoading = false
      this.notice = {
        id: '',
        notice_title: '',
        notice_type: '1',
        yesapi_sys_notice_status: 1,
        remark: '',
        content: ''
      }
    },
    handleInsertOrUpdateNoticeDialogClose() {
      this.$confirm('不继续编辑通知信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.resetNotice()
        this.query()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    handleNoticeUpdate() {
      this.$refs.notice_form.validate(valid => {
        if (valid) {
          this.$confirm('是否保存该通知信息?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('notice/updateNotice', this.notice)
              .then((resp) => {
                if (resp) {
                  this.$message.success('保存成功！')
                  setTimeout(() => {
                    this.resetNotice()
                    this.query()
                  }, 1500)
                }
              })
              .catch((error) => {
                this.$message.error(error)
              })
          }).catch(() => {
          })
        }
      })
    },
    handleUploadImage(event, insertImage, files) {
      let file = files[0]
      let formData = new FormData()
      formData.append("file", file)

      axios.post(`/adminSever/noticeBg/content-photo/${this.notice.id}`, formData, {
        headers: {
          token: getToken(),
        },
        'Content-Type': 'multipart/form-data'
      })
        .then((resp) => {
          if (resp.data.code === 1) {
            this.$notify({
              title: '提示',
              message: "需要控制图片大小时，在链接后添加'{{{width=\"宽度\" height=\"高度\"}}}' 即可控制",
              offset: 150,
              duration: 0
            });
            insertImage({
              url: this.returnUrl(resp.data.data),
              desc: resp.data.data.file_name
            });
          }
        })
        .catch((error) => {
          this.$message.error(error)
        })
    },
    returnUrl(data) {
      return this.server + data.bucket + "/" + data.url
    }
  }
}
</script>

<style scoped lang="scss">

</style>
